# encoding=utf-8
# 载入模块
import redis
import uuid
from globalsettings import CUR_MODE
if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *
# from globalsettings import REDIS_PORT, REDIS_IP, REDIS_PASS

if REDIS_PASS is None or REDIS_PASS == '':
    pool = redis.ConnectionPool(host=REDIS_IP, port=REDIS_PORT, db=0)
else:
    pool = redis.ConnectionPool(host=REDIS_IP, port=REDIS_PORT, password=REDIS_PASS, db=0)
r = redis.Redis(connection_pool=pool)
_r = redis.Redis(connection_pool=pool)


class RedisOper():
    def get(key):
        if _r.exists(key):
            # print("get key", key, ":", _r.get(key).decode('utf-8'))
            return str(_r.get(key).decode('utf-8'))
        else:
            return None

    def set(key, name):
        _r.set(key, str(name))
        _r.expire(key, 3600)

    def rpush(key, name):
        _r.rpush(key, str(name))

    def lpop(key):
        return _r.lpop(key)

    def llen(key):
        return _r.llen(key)

    def lindex(key, pos):
        return _r.lindex(key, pos)

    def lrem(key, value, num=0):
        _r.lrem(key, value, num)

    def delete(key):
        _r.delete(key)

    def set_token(user_id):
        struuid = user_id + '-' + str(uuid.uuid4()).replace("-", "")
        _r.set(user_id, struuid)
        return struuid

    def del_tokenbyuserid(user_id):
        _r.delete(user_id)

    def get_token_byuserid(user_id):
        token = None
        if (_r.exists(user_id)):
            token = _r.get(user_id).decode('utf-8')
        return token

    def get_userid_bytoken(token):
        try:
            token_substr = token.split('-')[-1]
            user_id = token.replace('-' + token_substr, '')
            get_token = None
            if (_r.exists(user_id)):
                get_token = _r.get(user_id).decode('utf-8')
            if get_token is None or get_token == '':
                return False, None
            if token == get_token:
                return True, user_id
            else:
                return False, None
        except Exception as e:
            print('token fail:', e)
            return False, None

    def get_permit_byuseridproductid(user_id, product_id):
        ket_str = 'permit_' + user_id + '_' + product_id
        rst = None
        if (_r.exists(ket_str)):
            rst = _r.get(ket_str)
        return rst

    def set_permit_byuseridproductid(user_id, product_id, result):
        _r.set('permit_' + user_id + '_' + product_id, result)

    def pub(channel, msg):
        _r.publish(channel, msg)

    def getsub(channel):
        p = _r.pubsub()
        if channel.index('*') > -1:
            p.psubscribe(channel)
        else:
            p.subscribe(channel)
        return p
        '''    for item in p.listen():
        print(item)
        if item['type'] == 'message' or item['type'] == 'pmessage':
            data = item['data']
            print(data.decode('utf-8'))
            if item['data'] == 'over':
                break
        '''

    def unsub(p, channel):
        if channel.index('*') > -1:
            p.punsubscribe(channel)
        else:
            p.unsubscribe(channel)

    def setid(key, value):
        _r.set(key, value)

    def incr(key):
        return _r.incr(key)

    def expire(key, time):
        _r.expire(key, time)

    def havekey(key):
        return _r.exists(key)

    def ttlkey(key):
        return _r.ttl(key)

    def checkkeytimes(key, times, count):
        # times = 5 # 多少秒统计
        # count = 7 # 每秒几次访问
        if RedisOper.havekey(key):
            ttl = RedisOper.ttlkey(key)
            if ttl is None or ttl < 0:
                intkey = RedisOper.incr(key)
                RedisOper.expire(key, times)
            elif ttl > times:
                RedisOper.expire(key, times)
            intkey = RedisOper.incr(key)
            # print(intkey)
            if intkey > times*count:
                RedisOper.expire(key, times*2)
                return False
            else:
                return True
        else:
            intkey = RedisOper.incr(key)
            RedisOper.expire(key, times)
            return True


if __name__ == "__main__":
    #     RedisOper.set("nvshen号", "hao好")
    #     print(RedisOper.get("nvshen号"))
    r.lpush('test', '11')
    r.lpush('test', '12')
    r.lpush('test', '13')
    r.lpush('test', '14')
    r.lpush('test', '15')
    i = 0
    while True:
        try:
            msg = r.brpop('test', timeout=3)
            print(i+1)
            print(msg)
        except Exception as e:
            print(e)
